var path = require('path');
var _ = require('underscore');
var config = require('./config');
var fs = require('fs');
var color = require('colors-cli');

var argv = require('yargs').argv;
var l = argv.l || false;
var r = argv.r || false;
var tag = argv._[0] || null;

//命令行回滚操作 （请避免project名称中间有空格，不解决该BUG哦）
//node back                   列出所有project
//node back -l admin          列出admin下的所有上传日志
//node back -r admin tag      回滚admin下的tag日志 tag支持1,2,3,回滚序号对应的Tag。   
if(r==false){
  if(typeof l =="string"){
    ListLogs(l);
  }else{
    ListProjects();
  }
}else{
  if(typeof r =="string"){
    if(tag !=null){
      back(r,tag);
    }else{
      console.log('argv error');
    }
  }
  else{
    console.log('argv error');
  }
}

function ListProjects(){
  if(config.projects.length < 1){
    console.log('请先配置 config.js文件');
  }
  config.projects.forEach(function(element) {
    console.log(color.cyan(element.name));
  }, this);
}

function ListLogs(name){
  var project = _.find(config.projects,function(p){return p.name ==name;});
  if(project == undefined){
    console.log('没有配置项目%s',color.cyan(name));
    return;
  }
  var logPath = path.resolve('data', name);
  GetLogs(logPath,function(files){
      _.forEach(files,function(p,index){
        var content = '['+ fs.readFileSync(p.directory + p.fullName,"utf-8") +'{}]';
        var log = JSON.parse(content)[0];        
        console.log('%d %s by %s %s %s',index+1
        ,color.cyan(p.name),color.green(log.account),log.data,color.yellow(log.memo));
      });
  });
}

function back(name,tag){
  var project = _.find(config.projects,function(p){return p.name ==name;});
  if(project == undefined){
    console.log('没有配置项目%s',color.cyan(name));
    return;
  }
  if (project.directory.substr(project.directory.length - 1) == "\\") {
    project.directory = project.directory.substr(0, project.directory.length - 1);
  }
  var logPath = path.resolve('data', name);
  GetLogs(logPath,function(files){
    _.forEach(files,function(p,index){
      if(p.name == tag || tag == (index+1)){
        console.log('开始执行回滚 %s',color.cyan(p.name));
        var content = '['+ fs.readFileSync(p.directory + p.fullName,"utf-8") +'{}]';
        var logs = JSON.parse(content).reverse();
        for(var i=1,item;item = logs[i];i++){
          if(item.old == '') {
            fs.unlink(project.directory+item.target);
            continue;
          }
          var copyFrom = path.resolve()+item.old;
          var copyTo = project.directory+item.target;
          console.log('copy %s to %s',copyFrom,copyTo );
          fs.createReadStream(copyFrom).pipe(fs.createWriteStream(copyTo));
        }
        fs.rename(p.directory + p.fullName,p.directory + p.fullName+'back');
        return;        
      };
    });
  });
}

//获取日志文件列表
function GetLogs(logPath, callback) {
  fs.readdir(logPath, function (err, files) {
    if (err) {
      console.log(err);
      return;
    }
    var list = [];
    if (files && files.length) {
      files.forEach(function (filename) {
        var filename = path.join(logPath, filename);
        var stats = fs.statSync(filename);
        if (stats.isFile()) {
          var fileInfo = FileFormat(filename);
          fileInfo.ctime = stats.ctime;
          if (fileInfo.extension == 'json') {
            list.push(fileInfo);
          }
        };
      });
      callback(_.sortBy(list, 'ctime').reverse());
    }
  });
}

function FileFormat(filePath) {
  var directory = ''; 
  var name = '';
  var extension = '';
  var hasExtension = true;
  var fullName = '';

  var index = filePath.lastIndexOf('\\');
  if (index != -1) {
    directory = filePath.substr(0, index + 1);
    filePath = filePath.substr(index + 1);
  }
  var index = filePath.lastIndexOf('.');
  if (index != -1) {
    fullName = filePath;
    name = filePath.substr(0, index);
    extension = filePath.substr(index + 1);
  } else {
    fullName = filePath;
    name = filePath;
    hasExtension = false;
  }
  return {
    directory: directory,
    fullName: fullName,
    name: name,
    extension: extension,
    hasExtension: hasExtension
  };
}